package edu.scsu.csci.converter;

import java.util.HashMap;
import java.util.Map;

import edu.scsu.csci.IConverter;
import edu.scsu.csci.core.IRegistry;


/**
 * A registory for all the convertors defined convertors.
 * 
 * @author Maqbool Khan
 * @since jdk 1.5
 * @see
 * @viz.diagram ConvertorRegistry.tpx
 */
public class ConvertorRegistry implements IRegistry<Class<?>, IConverter> {
	
	/**
	 * holds all the defined convertors.
	 */
	private Map<Class<?>, IConverter> registory;
	
	/**
	 * singleton.
	 */
	private static ConvertorRegistry instance;
	
	/**
	 * @return
	 */
	public synchronized static ConvertorRegistry getInstance(){
		if(instance == null){
			instance = new  ConvertorRegistry();
			instance.setUp();
		}
		return instance;
	}
	
	/**
	 * 
	 */
	private ConvertorRegistry(){
		this.registory = new HashMap<Class<?>, IConverter> ();
	}
	
	/**
	 * @param type
	 * @param convertor
	 */
	public void register(Class<?> type, IConverter convertor){
		this.registory.put(type, convertor);
	}
	
	/**
	 * @param type
	 * @return
	 */
	public IConverter get(Class<?> type){
		if(type == null){
			throw new IllegalArgumentException("Type " + type + " cannot be null.");
		}
		
		IConverter convertor = this.registory.get(type);
		if(convertor == null){
			throw new NoConvertorDefinedException("No convertor has been defined for type " + type);
		}
		return convertor;
	}
	
	/**
	 * Registers all the basic convertors.
	 */
	public void setUp(){
		this.register(Long.class, new SimpleLongConverter());
		this.register(long.class, new PrimitiveLongConverter());
		this.register(Integer.class, new SimpleIntegerConverter());
		this.register(int.class, new PrimitiveIntConverter());
		this.register(Float.class, new SimpleFloatConverter());
		this.register(float.class, new PrimitiveFloatConverter());
		this.register(Double.class, new SimpleDoubleConverter());
		this.register(double.class, new PrimitiveDoubleConverter());
		this.register(String.class, new StringConverter());
		this.register(Boolean.class, new SimpleBooleanConverter());
		this.register(boolean.class, new PrimitiveBooleanConverter());
		this.register(Short.class, new SimpleShortConverter());
		this.register(short.class, new PrimitiveShortConverter());
		this.register(Byte.class, new SimpleByteConverter());
		this.register(byte.class, new PrimitiveByteConverter());
		this.register(Character.class, new SimpleCharacterConverter());
		this.register(char.class, new PrimitiveCharConverter());
		this.register(java.util.Date.class, new UtilDateConverter());
		this.register(java.sql.Date.class, new SQLDateConverter());
	}
	
}
